import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { GetUserInfoModel, LoginParams } from '/@/api/system/model/userModel'
import { setAuthCache } from '/@/utils/auth'
import { TOKEN_KEY } from '/@/enums/cacheEnum'
import { router } from '/@/router'
import { PageEnum } from '/@/enums/pageEnum'
import { useGlobSetting } from "/@/hooks/setting";
import { JDragConfigEnum } from '/@/enums/jeecgEnum'
import {
  reqLogin,
  reqUserInfo,
  reqUserAll,
  reqUserList,
  reqUserAdd,
  getUserById,
  reqUserUpdate,
  reqUserDelete,
} from '../../api/system/user'
import type {
  loginResponseDate,
  userAllResponseData,
  userInfoData,
  userListFormData,
  userListResponseData,
} from '@/api/user/type'

interface UserState {
  // 用户信息
  userInfo: null
  // 用户token
  token: undefined
  // 角色列表
  roleList: []
  // 用户列表
  users: userInfoData[]
  // 菜单列表
  menuList: any[]
}

export const useUserStore = defineStore('app-user', () => {
  // 状态
  const userInfo = ref(null)
  const token = ref(undefined)
  const roleList = ref([])
  const users = ref<userInfoData[]>([])
  const menuList = ref<any[]>([])

  // getters
  const getUserInfo = computed(() => userInfo.value)
  const getToken = computed(() => token.value)
  const getRoleList = computed(() => roleList.value)
  const getMenuList = computed(() => menuList.value)

  // actions
  const setToken = (info: string | undefined) => {
    token.value = info ? info : ''
    setAuthCache(TOKEN_KEY, info)
  }

  const userLogin = async (params: LoginParams): Promise<GetUserInfoModel | null> => {
    try {
      const data = await reqLogin(params)
      if (data.status === 0 && data.data) {
        setToken(data.data.token)
        await getUserInfoAction()
      }
    } catch (error) {
      return Promise.reject(error)
    }
  }

  /**
   * 登录完成处理
   * @param goHome
   */
  const afterLoginAction = async (goHome?: boolean, data?: any): Promise<any | null> => {
    if (!getToken.value) return null
    //获取用户信息
    const userInfoData = await getUserInfoAction()
    if (userInfoData) {
      localStorage.setItem(JDragConfigEnum.DRAG_BASE_URL, useGlobSetting().domainUrl)
      let redirect = router.currentRoute.value?.query?.redirect as string
      // 判断是否有 redirect 重定向地址
      if (redirect && goHome) {
        const publicPath = import.meta.env.VITE_PUBLIC_PATH
        if (publicPath && publicPath != '/') {
          redirect = publicPath + redirect
        }
        // 当前页面打开
        window.open(redirect, '_self')
        return data
      }
      goHome && (await router.replace(PageEnum.BASE_HOME))
    }
    return data
  }

  const removeUser = async () => {
    console.log(userInfo.value)
    userInfo.value = null
    localStorage.removeItem('Vue3-User')
  }

  const getUserAll = async () => {
    const result: userAllResponseData = await reqUserAll()
    if (result.status == 0) {
      users.value = result.data as userInfoData[]
    } else {
      return Promise.reject(new Error(result.msg))
    }
  }

  const getUserList = async (data: userListFormData) => {
    const result: userListResponseData = await reqUserList(data)
    if (result.status == 0) {
      users.value = result.data?.data as userInfoData[]
      return result.data
    } else {
      return Promise.reject(new Error(result.msg))
    }
  }

  const addUser = async (data: userInfoData) => {
    const result: loginResponseDate = await reqUserAdd(data)
    if (result.status == 0) {
      return 'OK'
    } else {
      return Promise.reject(new Error(result.msg))
    }
  }

  const getUserById = async (_id: string) => {
    const result: loginResponseDate = await getUserById(_id)
    if (result.status == 0) {
      return result.data
    } else {
      return Promise.reject(new Error(result.msg))
    }
  }

  const updateUser = async (data: userInfoData) => {
    const result: loginResponseDate = await reqUserUpdate(data)
    if (result.status == 0) {
      return 'OK'
    } else {
      return Promise.reject(new Error(result.msg))
    }
  }

  const deleteUser = async (userId: string) => {
    const result: loginResponseDate = await reqUserDelete(userId)
    console.log(result.status)
    if (result.status == 0) {
      return 'OK'
    } else {
      return Promise.reject(new Error(result.msg))
    }
  }

  const getUserInfoAction = async () => {
    const result: loginResponseDate = await reqUserInfo()
    console.log(result)
    if (result.status == 0) {
      userInfo.value = result.data as userInfoData
      localStorage.setItem('Vue3-User', JSON.stringify(result.data) as string)
    } else {
      return Promise.reject(new Error(result.msg))
    }
  }

  return {
    // 状态
    userInfo,
    token,
    roleList,
    users,
    menuList,
    // getters
    getUserInfo,
    getToken,
    getRoleList,
    getMenuList,
    // actions
    setToken,
    userLogin,
    afterLoginAction,
    removeUser,
    getUserAll,
    getUserList,
    addUser,
    getUserById,
    updateUser,
    deleteUser,
    getUserInfoAction,
  }
})
